from rest_framework.mixins import ListModelMixin
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from .models import Banner
from .serializers import BannerSerizlizer
from django.conf import settings
from django.core.cache import cache
from rest_framework.response import Response
# Create your views here.
from app01.utils.loggings import logger
# 第一步：导入Redis类
from redis import Redis
from app01.utils.response import APIResponse



class BannerViewSet(GenericViewSet, ListModelMixin):
    queryset = Banner.objects.all().filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNT]
    serializer_class = BannerSerizlizer

    def list(self, request, *args, **kwargs):
        banner_list=cache.get('banner_list_cache')
        if banner_list:
            logger.info('走了缓存')
            return Response(data=banner_list)
        else:
            res = super().list(request, *args, **kwargs)
            logger.info('走了mysql')
            cache.set('banner_list_cache',res.data)
            return res

class Notice(APIView):
    def get(self,request):
        conn = Redis(host="localhost", port=6379, )
        list_length = conn.llen('gg')
        old_length = str(conn.get('length'), 'utf-8')
        res = int(list_length) - int(old_length)
        conn.set('length', res, xx=True)
        gg_list = []
        if res > 0:
            for i in range(0, res-1):
                obj = str(conn.lpop('gg'), 'utf-8')
                gg_list.append(obj)
        conn.close()
        return APIResponse(data=gg_list)




